﻿using System;
using System.Collections.Generic;
using System.Text;
using Autofac;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace duia.Canteenpay.Infrastructure.Domain
{
    /// <summary>
    /// Autofac
    /// </summary>
    public static class AutofacBuilder
    {
        /// <summary>
        /// Autofac容器
        /// </summary>
        private static IServiceProvider _container;

        /// <summary>
        /// 方法注入
        /// </summary>
        /// <param name="container"></param>
        public static void InitContainer(IServiceProvider container)
        {
            _container = container;
        }

        /// <summary>
        /// 获取容器注入对象，非请求生命周期内的注入对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetService<T>()
        {
            return _container.GetService<T>();

        }

        /// <summary>
        /// 获取容器全部实现注入对象，非请求生命周期内的注入对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static IEnumerable<T> GetServices<T>()
        {
            return _container.GetServices<T>();

        }

        /// <summary>
        /// 获取请求生命周期内的注入对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetHttpService<T>()
        {

            return _httpContextAccessor.HttpContext.RequestServices.GetService<T>();

        }

        /// <summary>
        /// 获取请求生命周期内的注入对象-全部实现
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static IEnumerable<T> GetHttpServices<T>()
        {
            return _httpContextAccessor.HttpContext.RequestServices.GetServices<T>();
        }

        /// <summary>
        /// 获取请求生命周期对象IHttpContextAccessor
        /// </summary>
        public static IHttpContextAccessor _httpContextAccessor
        {
            get
            {
                var httpContextAccessor = _container.GetService<IHttpContextAccessor>();
                if (httpContextAccessor == null)
                {
                    throw new Exception("IHttpContextAccessor is null, please inject in startup IHttpContextAccessor");
                }
                return httpContextAccessor;
            }
        }
    }
}
